package com.yanqu.road.server.gameplayer.module.activity.tomb.cmd;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.tomb.Tomb;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.tomb.TombMgr;
import com.yanqu.road.server.gameplayer.module.activity.tomb.TombModule;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.sync.message.SyncResponse;

import java.util.concurrent.CompletableFuture;


@Cmd(code = GameProtocol.S_TOMB_REPAIR_RANK,desc = "秦俑在世排行请求")
public class TombGetRepairRankCmd extends AbstractCommand {

    private Tomb.TombRepairRankReq req;

    private Tomb.TombRepairRankResp.Builder repairRankRespBuilder;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        req = Tomb.TombRepairRankReq.parseFrom(packet.getBytes());
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        repairRankRespBuilder = Tomb.TombRepairRankResp.newBuilder();
        ActivityInfo activityInfo = TombMgr.getActivityInfo();
        if (activityInfo == null) {
            this.repairRankRespBuilder.setRet(GameErrorCode.E_ACTIVITY_NOT_OPEN);
            player.sendPacket(ClientProtocol.U_TOMB_REPAIR_RANK, this.repairRankRespBuilder);

            return;
        }

        int ret = player.getModule(TombModule.class).isOpen(false);
        if (ret > 0) {
            this.repairRankRespBuilder.setRet(ret);
            player.sendPacket(ClientProtocol.U_TOMB_REPAIR_RANK, this.repairRankRespBuilder);
            return;
        }

        CompletableFuture<SyncResponse> future = GamePlayerMgr.sendToActivityCrossServerForUnionGroup(player.getUserId(), CrossProtocol.C_TOMB_REPAIR_RANK, activityInfo.getActivityId(), null, this.repairRankRespBuilder);
        future.thenAccept(syncResponse -> {
            if (!this.repairRankRespBuilder.hasRet()) {
                this.repairRankRespBuilder.setRet(0);
            }
            player.sendPacket(ClientProtocol.U_TOMB_REPAIR_RANK,this.repairRankRespBuilder);
        });



    }

    @Override
    public void sendData(GamePlayer player) {
        if (this.repairRankRespBuilder.getRet() != 0) {
            player.sendPacket(ClientProtocol.U_TOMB_REPAIR_RANK, this.repairRankRespBuilder);
        }
    }
}
